require 'rails/all'
require 'rails/generators/resource_helpers'
class EcCrudGenerator < Rails::Generators::NamedBase
  include Rails::Generators::ResourceHelpers
  source_root File.expand_path('../templates', __FILE__)

  argument :controller, type: :string, default: '', banner: "controller_full_name"

  def append_actions_to_controller
    active_record_class = @controller_name.singularize
    instance_obj = @controller_file_name.singularize
    append_template_name = 'con.rb'
    path = target_path
    if path
      source = File.expand_path(find_in_source_paths(append_template_name))
      context = instance_eval("binding")
      append_to_file "#{File.join("app/controllers", path[1])}.rb" do
        content = ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context)
        content
      end
    end
  end

  def create_root_folder
    path = target_path
    if path
      empty_directory File.join("app/views", path[0])
    end
  end

  def copy_view_files
    path = target_path
    if path
      available_views.each do |view|
        filename = [view, :html, :erb].compact.join(".")
        template filename, File.join("app/views", path[0], filename)
      end
    end
  end

  protected

  def available_views
    %w(_form new edit index)
  end

  def target_path
    nil
    if $*[1] && !$*[1].blank?
      ec_controller_names = $*[1].split('::')
      [ec_controller_names.map { |m| m.underscore.gsub(/_controller/, '') }, ec_controller_names.map { |m| m.underscore }]
    end
  end
end

# require 'rails/generators/erb'
# require 'rails/generators/resource_helpers'
#
# module Erb # :nodoc:
#   module Generators # :nodoc:
#     class ScaffoldGenerator < Base # :nodoc:
#       include Rails::Generators::ResourceHelpers
#
#       argument :attributes, type: :array, default: [], banner: "field:type field:type"
#
#       def create_root_folder
#         empty_directory File.join("app/views", controller_file_path)
#       end
#
#       def copy_view_files
#         available_views.each do |view|
#           formats.each do |format|
#             filename = filename_with_extensions(view, format)
#             template filename, File.join("app/views", controller_file_path.singularize, filename)
#           end
#         end
#       end
#
#       protected
#
#       def available_views
#         %w(index edit show new _form)
#       end
#     end
#   end
# end
